package com.rk.kbk.controller;


import com.rk.kbk.common.*;
import com.rk.kbk.controller.util.PayUtils;
import com.rk.kbk.controller.util.PayUtilsRide;
import com.rk.kbk.controller.util.wxpay.util.WXpayCore;
import com.rk.kbk.controller.util.wxpay.util.WXpayXmlUtils;
import com.rk.kbk.controller.util.wxpayRide.util.WXpayCoreRide;
import com.rk.kbk.dao.AccountDao;
import com.rk.kbk.dao.CashRecordDao;
import com.rk.kbk.dao.UserDao;
import com.rk.kbk.dto.PageDto;
import com.rk.kbk.model.Account;
import com.rk.kbk.model.CashRecord;
import com.rk.kbk.model.User;
import com.rk.kbk.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @AccountController
 * @用户商家账户Controller
 * @version : Ver 1.0
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/account")
public class AccountController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private UserService userService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CashRecordDao cashRecordDao;
    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    private SqlToResult sqlToResult;
    public static String wxnotify = "/api/account/wxpay/success";

    /**
     * @添加/修改用户商家账户
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateAccount",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateAccount(){
        log.debug("添加/修改用户商家账户");
       String sql="select * from account";
  /*      Query query=entityManager.createNativeQuery(sql);
        //每一个对象数组存的是相应的实体属性
        List objecArraytList = query.getResultList();
        List list=new ArrayList();
        for(int i=0;i<objecArraytList.size();i++) {
            Object[] obj = (Object[]) objecArraytList.get(i);
            //使用obj[0],obj[1],obj[2]...取出属性　　
            for(int m=0;m<obj.length;m++){
                list.add(obj[m]);
            }
        }*/


//        entityManager.close();
        Object resultList = sqlToResult.getResultList(sql,"one");
        List<Object> o = (List) resultList;
        List<Account> accounts = new ArrayList<>();
        o.forEach(n -> accounts.add(PubLib.copyObject(n, Account.class)));
        return JsonResp.ok(accounts);
    }

    /**
     * @批量添加/修改用户商家账户
     * @param accounts
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateSomeAccount",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateSomeAccount(@RequestBody List<Account> accounts){
        log.debug("批量添加/修改用户商家账户");
        accountDao.save(accounts);
        return JsonResp.ok();
    }
    /**
     * @发单前  查看押金余额（不足200无法发单）
     *
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/findDepositMoneyByUser",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findDepositMoneyByUser(Long shopId){
        log.debug("查看押金余额");
     //   JsonResp jsonResp=userService.findLoginUser();
        User shop=userDao.findOne(shopId);
        Account account=accountDao.findByUser(shop);
        boolean flag=false;
        if(new BigDecimal(account.getDepositMoney().toString()).compareTo(new BigDecimal("200"))>=0){
            flag=true;
        }
        if(flag){
            return JsonResp.ok(flag);
        }else{
            return JsonResp.fa("押金小于200元！");
        }
    }


    /**
     * @押金（余额）转账到金额（押金）
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/runningAccount",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp runningAccount(String moneyCount,int type,Long userId) {
        log.debug("押金（余额）转账到金额（押金）");
        User user = userDao.findOne(userId);
        Account account = accountDao.findByUser(user);
        Double allMoney = account.getAllMoney();//余额
        Double depositMoney = account.getDepositMoney();//押金
        BigDecimal bd_depositMoney = new BigDecimal(depositMoney.toString());
        BigDecimal bd_allMoney = new BigDecimal(allMoney.toString());
        BigDecimal bd_depositMoneyCount = new BigDecimal(moneyCount);
        String str=null; int payType=-1;
        if(type==1) {//押金转账到余额
            if (bd_depositMoney.compareTo(new BigDecimal(moneyCount)) >= 0) {
                Double saveAllMoney = bd_allMoney.add(bd_depositMoneyCount).doubleValue();//余额加转账金额
                Double saveDepositMoney = bd_depositMoney.subtract(bd_depositMoneyCount).doubleValue();//押金减转账金额
                account.setAllMoney(saveAllMoney);
                account.setDepositMoney(saveDepositMoney);
                accountDao.save(account);
                str="押金转余额";payType=4;
            } else {
                return JsonResp.fa("押金数额不足");
            }
        }else if(type==2){//余额转账到押金
            if (bd_allMoney.compareTo(new BigDecimal(Double.valueOf(moneyCount))) > 0) {
                Double saveAllMoney = bd_allMoney.subtract(bd_depositMoneyCount).doubleValue();//余额减转账金额
                Double saveDepositMoney = bd_depositMoney.add(bd_depositMoneyCount).doubleValue();//押金加转账金额
                account.setAllMoney(saveAllMoney);
                account.setDepositMoney(saveDepositMoney);
                accountDao.save(account);
                str="余额转押金";payType=1;
            } else {
                return JsonResp.fa("余额不足！");
            }
        }
        /*****************记录账户明细 （押金加或减钱）**********************/
        CashRecord cashRecord=new CashRecord();
        cashRecord.setUser(user);
        cashRecord.setTitle(str);
        cashRecord.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
        cashRecord.setOrderType(3);//1表示配送订单，2表示商城订单，3表示其他
        cashRecord.setRecoedType(1);//流水类型，1表示充值，2表示提现，3表示消费扣钱
        if(payType==4){
            cashRecord.setMoney(-bd_depositMoneyCount.doubleValue());
            cashRecord.setRechargeType(4);
        }else if(payType==1){
            cashRecord.setMoney(bd_depositMoneyCount.doubleValue());
            cashRecord.setRechargeType(5);
        }
        cashRecord.setPayType(payType);//支付类型：1表示余额支付，2表示支付宝支付，3表示微信支付,4押金支付
        cashRecord.setMoneyType(2);//1表示余额，2表示押金
        if(user.getUserType()==2){//用户类型,1表示用户，2表示骑手，3表示商家
            cashRecord.setGivePerson(2);
            cashRecord.setReceivePerson(2);
        }else if(user.getUserType()==3){
            cashRecord.setGivePerson(1);
            cashRecord.setReceivePerson(1);
        }
        cashRecordDao.save(cashRecord);
     /*****************记录账户明细 （余额加或减钱）**********************/
        CashRecord cashRecord2=new CashRecord();
        cashRecord2.setUser(user);
        cashRecord2.setTitle(str);
        cashRecord2.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
        cashRecord2.setOrderType(3);//1表示配送订单，2表示商城订单，3表示其他
        cashRecord2.setRecoedType(1);//流水类型，1表示充值，2表示提现，3表示消费扣钱
        if(payType==4){
            cashRecord2.setMoney(bd_depositMoneyCount.doubleValue());
            cashRecord2.setRechargeType(4);
        }else if(payType==1){
            cashRecord2.setMoney(-bd_depositMoneyCount.doubleValue());
            cashRecord2.setRechargeType(5);
        }
        cashRecord2.setPayType(payType);//支付类型：1表示余额支付，2表示支付宝支付，3表示微信支付,4押金支付
        cashRecord2.setMoneyType(1);//1表示余额，2表示押金
        if(user.getUserType()==2){//用户类型,1表示用户，2表示骑手，3表示商家
            cashRecord2.setGivePerson(2);
            cashRecord2.setReceivePerson(2);
        }else if(user.getUserType()==3){
            cashRecord2.setGivePerson(1);
            cashRecord2.setReceivePerson(1);
        }
        cashRecordDao.save(cashRecord2);
        return JsonResp.ok();
    }

    /**
     * @分页查询用户账户(jpa方式)
     * @param userType 用户类型
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/page",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageAccountJpa(Integer pageNum, Integer pageSize,String search,Integer isRegister,Integer userType) {
        log.debug("分页查询用户账户(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
            Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
            Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
            Page page = null;
            if(StringUtils.isEmpty(search) && isRegister == -1){
                page = accountDao.findAll( 		  //按用户类型分页
                        (root, criteriaQuery, cb) -> {
                            Predicate predicate=cb.conjunction();
                            List<Expression<Boolean>> expressions = predicate.getExpressions();
                            List<User> users = userDao.findByUserType(userType);
                            if (users.size()==0){
                                CriteriaBuilder.In<Object> stick = cb.in(root.get("user"));
                                expressions.add(stick.value(0));
                            }else{
                                List<Long> ids = users.stream().map(User::getId).collect(Collectors.toList());
                                //in
                                CriteriaBuilder.In<Object> stick = cb.in(root.get("user"));
                                for (Long l1 : ids) {
                                    expressions.add(stick.value(l1));
                                }
                            }
                            return predicate;
                        }, pageable);
            }else{
                page = accountDao.findAll( 		  //条件分页
                        (root, criteriaQuery, cb) -> {
                            Predicate predicate=cb.conjunction();
                            List<Expression<Boolean>> expressions = predicate.getExpressions();
                            //isRegister判断
                            List<User> users2;
                            if (isRegister == -1){
                                users2 = userDao.findByUserType(userType);
                            }else{
                                users2 = userDao.findByUserTypeAndIsRegisterAndUserStatus(userType,isRegister, 1);
                            }
                                List<Long> ids2 = users2.stream().map(User::getId).collect(Collectors.toList());
                                //in
                            if(users2!=null&&!users2.isEmpty()){
                                CriteriaBuilder.In<Object> stick1 = cb.in(root.get("user"));
                                for (Long l2 : ids2) {
                                    expressions.add(stick1.value(l2));
                                }
                            }else{
                                CriteriaBuilder.In<Object> stick1 = cb.in(root.get("user"));
                                expressions.add(stick1.value(0));
                            }
                            //模糊查询
                            List<User> users3 = userDao.findByPhoneLike("%"+search+"%");
                            List<Long> ids3 = users3.stream().map(User::getId).collect(Collectors.toList());
                            if(users3!=null&&!users3.isEmpty()){
                                CriteriaBuilder.In<Object> stick2 = cb.in(root.get("user"));
                                for (Long l3 : ids3) {
                                    expressions.add(stick2.value(l3));
                                }
                            }else{
                                CriteriaBuilder.In<Object> stick2 = cb.in(root.get("user"));
                                expressions.add(stick2.value(0));
                            }


/*                            Long l = 0L;
                            try{
                                l = Long.parseLong(search);
                            }catch(Exception ignored){
                            }

                            List<User> users = userDao.findByUserTypeAndIdLikeOrNickNameLikeOrPhoneLike(userType,l, "%"+search+"%", "%"+search+"%");

                            if (users == null || users.isEmpty()) {
                                expressions.add(cb.equal(root.get("user"), l));
                            }

                            List<Long> ids = users.stream().map(User::getId).collect(Collectors.toList());
                            //in
                            CriteriaBuilder.In<Object> stick = cb.in(root.get("user"));
                            for (Long l1 : ids) {
                                expressions.add(stick.value(l1));
                            }*/


                            return predicate;
                        }, pageable);
            }
            return JsonResp.ok(new PageDto(page));
    }

    /**
     * @分页查询可以指派的骑手(jpa方式)
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/accountCanSendOrderJpa",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageAccountCanSendOrderJpa(Integer pageNum, Integer pageSize) {
        log.debug("分页查询可以指派的骑手(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
            page = accountDao.findAll(
                    (root, criteriaQuery, cb) -> {
                        Predicate predicate=cb.conjunction();
                        List<Expression<Boolean>> expressions = predicate.getExpressions();
                        List<User> users = userDao.findByUserTypeAndIsWorkAndIsRegisterAndUserStatusAndServeType(2,1,1,1,1);
                        if (users.size()==0){
                            CriteriaBuilder.In<Object> stick = cb.in(root.get("user"));
                            expressions.add(stick.value(0));
                        }else{
                            List<Long> ids = users.stream().map(User::getId).collect(Collectors.toList());
                            //in
                            CriteriaBuilder.In<Object> stick = cb.in(root.get("user"));
                            for (Long l1 : ids) {
                                expressions.add(stick.value(l1));
                            }
                        }
                        return predicate;
                    }, pageable);
        return JsonResp.ok(new PageDto(page));
    }

    /**
     * @删除用户商家账户-one(永久)
     * @param accountId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteAccountOne",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteAccountOne(Long accountId) {
        log.debug("删除用户商家账户-one(永久aaa)");
        accountDao.delete(accountId);
        return JsonResp.ok();
    }

    /**
     * @押金充值
     * @param money 金额
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/depositRecharge",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp depositRecharge(Long userId, Double money, Integer type, HttpServletRequest request) {
        log.debug("押金充值");
        User user=userDao.findOne(userId);
        Integer userType=user.getUserType();
        Account account=accountDao.findByUser(user);
        String title="";
        if(type==1){//余额充值
            Double allMoney=account.getAllMoney();
            Double depositMoney=account.getDepositMoney();
            if(new BigDecimal(String.valueOf(allMoney)).compareTo(new BigDecimal(String.valueOf(money)))<0){
                return  JsonResp.fa("账户余额不足");
            }else {
                account.setAllMoney(new BigDecimal(String.valueOf(allMoney)).subtract(new BigDecimal(String.valueOf(money))).doubleValue());
                account.setDepositMoney(new BigDecimal(String.valueOf(depositMoney)).add(new BigDecimal(String.valueOf(money))).doubleValue());
                accountDao.save(account);
                //-----------------------------记录明细（余额减钱）---------------------------
                title="押金充值(余额)";
                //保存余额支付记录
                CashRecord cashRecord = new CashRecord();
                cashRecord.setUser(user);
                cashRecord.setTitle(title);
                cashRecord.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                //  cashRecord.setOrderNumber();
                cashRecord.setOrderType(3);//1表示配送订单，2表示商城订单，3表示其他
                //  cashRecord.setOrderNumber(order.getOrderNumber());//订单编码
                cashRecord.setRecoedType(1);//流水类型，1表示充值，2表示提现，3表示消费扣钱
                cashRecord.setRechargeType(5);
                cashRecord.setMoney(-money);
                cashRecord.setMoneyType(1);
                cashRecord.setPayType(1);//支付类型：1表示余额支付，2表示支付宝支付，3表示微信支付
                cashRecord.setStatus(1);
                if(user.getUserType()==2){//骑手
                    cashRecord.setGivePerson(2);
                    cashRecord.setReceivePerson(2);
                }else if(user.getUserType()==3){//商家
                    cashRecord.setGivePerson(1);
                    cashRecord.setReceivePerson(1);
                }
                cashRecordDao.save(cashRecord);//保存支付记录
                //---------------------------记录明细（押金加钱）---------------------------
                title="押金充值(余额)";
                //保存余额支付记录
                CashRecord cashRecord2 = new CashRecord();
                cashRecord2.setUser(user);
                cashRecord2.setTitle(title);
                cashRecord2.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                //  cashRecord.setOrderNumber();
                cashRecord2.setOrderType(3);//1表示配送订单，2表示商城订单，3表示其他
                //  cashRecord.setOrderNumber(order.getOrderNumber());//订单编码
                cashRecord2.setRecoedType(1);//流水类型，1表示充值，2表示提现，3表示消费扣钱
                cashRecord2.setMoney(money);
                cashRecord2.setMoneyType(2);
                cashRecord2.setRechargeType(5);
                cashRecord2.setPayType(1);//支付类型：1表示余额支付，2表示支付宝支付，3表示微信支付
                cashRecord2.setStatus(1);
                if(user.getUserType()==2){//骑手
                    cashRecord2.setGivePerson(2);
                    cashRecord2.setReceivePerson(2);
                }else if(user.getUserType()==3){//商家
                    cashRecord2.setGivePerson(1);
                    cashRecord2.setReceivePerson(1);
                }
                cashRecordDao.save(cashRecord2);//保存支付记录

            }
        }else if(type==2){//支付宝充值

        }else if(type==3){//微信充值
            String sym = request.getRequestURL().toString().split("/api/")[0];
            String trade_no = (user.getId() + "a" + UUID.randomUUID().toString().replaceAll("-", "").toLowerCase()).substring(0,32);
            Map map=null;
//            String json=null;
            if(userType==2){//骑手微信支付
                map = PayUtilsRide.WxPay(trade_no, money, "押金充值", sym + wxnotify);
                System.out.print("--------"+sym + wxnotify);
            }else if(userType==3){//商户微信支付
                map = PayUtils.WxPay(trade_no, money, "押金充值", sym + wxnotify);
                System.out.print("--------"+sym + wxnotify);

            }
            if (map != null) {
                return JsonResp.ok("支付成功",map);
            }else{
                throw new FailException();
            }

        }
        return JsonResp.ok();
    }

    @RequestMapping(value = "/wxpay/success",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public String wxpaySucc(HttpServletRequest request,HttpServletResponse response) throws IOException {
        System.out.println("微信支付回调");
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        String resultxml = new String(outSteam.toByteArray(), "utf-8");
        Map<String, String> params = WXpayXmlUtils.xml2map(resultxml);
        log.debug("。。。。。。。。。。。patams="+params);
        outSteam.close();
        inStream.close();
        Long userId = Long.valueOf(params.get("out_trade_no").split("a")[0]);
        User user = userDao.findOne(userId);
        Integer userType = user.getUserType();
        if(userType==2){//骑手端
            if (!WXpayCoreRide.checkSign(params)) {
                // 支付失败
                return "fail";
            }
        }else if(userType==3){
            if (!WXpayCore.checkSign(params)) {
                // 支付失败
                return "fail";
            }
        }
            System.out.println("===============付款成功==============");
            // ------------------------------
            // 处理业务开始
            // 此处处理订单状态，结合自己的订单数据完成订单状态的更新
            String total_fee = params.get("total_fee");
            double money = Double.valueOf(total_fee) / 100;
            Account account = accountDao.findByUser(user);
            Double addMoney = new BigDecimal(String.valueOf(account.getDepositMoney())).add(new BigDecimal(String.valueOf(money))).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
            account.setDepositMoney(addMoney);
            accountDao.save(account);
            /***************************支付明细*********************************/
            CashRecord cashRecord = new CashRecord();
            cashRecord.setUser(user);
            String title = "押金充值(微信)";
            cashRecord.setTitle(title);
            cashRecord.setTransactionNum(params.get("transaction_id"));//交易单号
            // cashRecord.setOrderNumber();
            cashRecord.setOrderType(3);//1表示配送订单，2表示商城订单，3表示其他
            //  cashRecord.setOrderNumber(orderNumber);//订单编码
            cashRecord.setRecoedType(1);//流水类型，1表示充值，2表示提现，3表示消费扣钱
            cashRecord.setMoney(money);
            cashRecord.setMoneyType(2);//押金
            cashRecord.setPayType(3);//支付类型：1表示余额支付，2表示支付宝支付，3表示微信支付
            cashRecord.setStatus(1);
            if (userType == 2) {
                cashRecord.setGivePerson(2);
                cashRecord.setReceivePerson(2);
            } else if (userType == 3) {
                cashRecord.setGivePerson(1);
                cashRecord.setReceivePerson(1);
            }
            cashRecordDao.save(cashRecord);//保存支付记录

            return "success";
        }
//    }




    /**
     * @查看骑手押金剩余（不足200无法接单）
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/findAccountDepositMoney",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findAccountDepositMoney(Long rideId) {
        log.debug("查看骑手押金剩余（不足200无法接单）");
        User user = userDao.findOne(rideId);
        Account account = accountDao.findByUser(user);
        Double depositMoney = account.getDepositMoney();
        BigDecimal bd1 = new BigDecimal(depositMoney);
        if (bd1.compareTo(new BigDecimal("200")) < 0) {
            return JsonResp.ok("押金不足200不能下单");
        } else {
            return JsonResp.ok();
        }
    }


    /**
     * @批量删除用户商家账户(永久)
     * @param accounts
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteSomeAccount",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteSomeAccount(@RequestBody List<Account> accounts) {
        log.debug("批量删除用户商家账户(永久)");
        accountDao.delete(accounts);
        return JsonResp.ok();
    }


    /**
     * @查看账户中的余额和押金
     * @param userId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/findAccountByShopId",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findAccountByShopId(Long userId) {
        log.debug("查看账户中的余额和押金");
           User user=userDao.findOne(userId);
            Account account=accountDao.findByUser(user);
            Map map =new HashMap();
            map.put("allMoney",account.getAllMoney());
            map.put("depositMoney",account.getDepositMoney());
            map.put("blockDepositMoney",account.getBlockDepositMoney());
            map.put("userId",userId);
            return JsonResp.ok(map);


    }

    /**
     * @return 返回值JsonResp
     * @用户总金额信息
     */
    @RequestMapping(value = "/allUserAccount",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp allUserAccount(){
        log.debug("用户总金额信息");
        //商家总余额
        String sqlone="SELECT ifnull(ROUND(sum(account.all_money),2),0) as shopAll from account,`user` WHERE account.`user`=`user`.id and account.`status`=1 and `user`.user_type=3 and user.user_status=1 ";
        Object resultListone = sqlToResult.getResultList(sqlone, "one");
        Map mapone = PubLib.copyObject(resultListone, Map.class);
        //商家总押金
        String sqltwo="SELECT ifnull(ROUND(sum(account.deposit_money),2),0) as shopDeposit from account,`user` WHERE account.`user`=`user`.id and account.`status`=1 and `user`.user_type=3 and user.user_status=1 ";
        Object resultListtwo = sqlToResult.getResultList(sqltwo, "one");
        Map maptwo = PubLib.copyObject(resultListtwo, Map.class);
        //骑手总余额
        String sqlthree="SELECT ifnull(ROUND(sum(account.all_money),2),0) as riderAll from account,`user` WHERE account.`user`=`user`.id and account.`status`=1 and `user`.user_type=2 and user.user_status=1 ";
        Object resultListthree = sqlToResult.getResultList(sqlthree, "one");
        Map mapthree = PubLib.copyObject(resultListthree, Map.class);
        //骑手总押金
        String sqlfour="SELECT ifnull(ROUND(sum(account.deposit_money),2),0) as riderDeposit from account,`user` WHERE account.`user`=`user`.id and account.`status`=1 and `user`.user_type=2 and user.user_status=1 ";
        Object resultListfour = sqlToResult.getResultList(sqlfour, "one");
        Map mapfour = PubLib.copyObject(resultListfour, Map.class);
        //支付宝充值金额
        String sqlfive="SELECT IFNULL(ROUND(SUM(money),2),0) as zhiFuBao FROM cash_record WHERE  pay_type=2 and  recoed_type=1 ";
        Object resultListfive = sqlToResult.getResultList(sqlfive, "one");
        Map mapfive = PubLib.copyObject(resultListfive, Map.class);
        //微信充值金额
        String sqlsix="SELECT IFNULL(ROUND(SUM(ABS(money)),2),0) AS WeiXin FROM cash_record WHERE  pay_type=3 AND  recoed_type IN(1,3) ";
        Object resultListsix= sqlToResult.getResultList(sqlsix, "one");
        Map mapsix = PubLib.copyObject(resultListsix, Map.class);
        //已提现金额
        String sqlseven="SELECT IFNULL(ROUND(SUM(money),2),0) as drawMoney FROM cash_record WHERE withdraw_status=2 and  recoed_type=2 ";
        Object resultListseven= sqlToResult.getResultList(sqlseven, "one");
        Map mapseven = PubLib.copyObject(resultListseven, Map.class);
        //罚款金额
        String sqleight="SELECT ifnull(ROUND(sum(punish_money),2),0) as punishMoney FROM `punish_log` WHERE punish_type=2 ";
        Object resultListeight= sqlToResult.getResultList(sqleight, "one");
        Map mapeight = PubLib.copyObject(resultListeight, Map.class);
        //待处理金额
        String sqlnine="SELECT ((select IFNULL(sum(send_money), 0) + IFNULL(sum(order_tip),0) + IFNULL(SUM(change_money),0) FROM orders WHERE order_status in(1,2)) + (SELECT IFNULL(SUM(pay_money),0) from order_goods WHERE order_status in(0,1)) ) as undealMoney ";
        Object resultListnine= sqlToResult.getResultList(sqlnine, "one");
        Map mapnine = PubLib.copyObject(resultListnine, Map.class);
        //服务费总额
        String sqlten="SELECT  IFNULL(ROUND(SUM(((orders.change_money+orders.order_tip+orders.send_money)*`user`.service_rate)),2),0) as serveMoney  FROM orders ,`user` Where orders.ride=`user`.id and orders.order_status=4 ";
        Object resultListten= sqlToResult.getResultList(sqlten, "one");
        Map mapten = PubLib.copyObject(resultListten, Map.class);
        //奖励金额
        String sqlele="SELECT ifnull(ROUND(sum(punish_money),2),0) as pariseMoney FROM `punish_log` WHERE punish_type=3 ";
        Object resultListele= sqlToResult.getResultList(sqlele, "one");
        Map mapele = PubLib.copyObject(resultListele, Map.class);
        //冻结押金总额
        String sqltwe="SELECT IFNULL(SUM(block_deposit_money),0) as blockDeposit FROM account WHERE status=1";
        Object resultListtwe= sqlToResult.getResultList(sqltwe, "one");
        Map maptwe = PubLib.copyObject(resultListtwe, Map.class);
        List<Map> list =new ArrayList<>();
        list.add(mapone);
        list.add(maptwo);
        list.add(mapthree);
        list.add(mapfour);
        list.add(mapfive);
        list.add(mapsix);
        list.add(mapseven);
        list.add(mapeight);
        list.add(mapnine);
        list.add(mapten);
        list.add(mapele);
        list.add(maptwe);
        return JsonResp.ok(list);
    }




}
